const path = require('path')
const {BrowserWindow, ipcMain, globalShortcut } = require('electron')
const { enable } = require('@/common/winUtils/enable')
const config = require("@/common/winUtils/config");
let {ico} = config.getAppConfig()

let win = null, secret = ''

const sendToWin = (channel, data) => {
  if (win && !win.isDestroyed()) {
    win.webContents.send(channel, data)
  } else {
    if (this.secret) {
      shopWin.createWin(this.secret, () => {
        win.webContents.send(channel, data)
      }, false)
    }
  }
}

const shopWin = {
  createWin: (secret, fun = null, show = true) => {
    this.secret = secret
    win = new BrowserWindow({
      width: 1200,
      height: 800,
      title: '网吧商品超市',
      backgroundColor: '#00000000',
      resizable: false,
      maximizable: false,
      transparent: true,
      frame: false,
      show: show,
      icon: ico,
      webPreferences: {
        partition: String(+new Date()),
        plugins: true,
        nodeIntegration: true,
        contextIsolation: false,
        webViewTag: true,
        webSecurity: false,
        enableRemoteModule: true
      }
    })
    win.setMenu(null)
    globalShortcut.register('CommandOrControl+Shift+u', function () {
      win.webContents.openDevTools()
    })
    if (process.env.ENV == 'development') {
      win.loadURL(`${process.env.VUE_APP_WEB_DOMAIN}/home?tab=1&secret=${encodeURIComponent(secret)}`, { extraHeaders: "pragma: no-cache\n" });
    } else {
      win.loadURL(`file://${path.join(__dirname, 'index.html')}#/home?tab=1&secret=${secret}`);
    }
    win.webContents.on('did-finish-load', () => {
      if(fun)fun()
    });
    enable(win)
    win.on('closed', () => {
      win = null
    })
    win.once('ready-to-show', () => {
      if (show) win.show()
    })
    ipcMain.on('window-shop-min', function () {
      if(win) win.hide()
    })
    ipcMain.on('window-shop-close', function () {
      if(win) win.close()
    })
    ipcMain.on('call-network', () => {
      sendToWin('call-network')
    })
    ipcMain.on("change-tab", (event, tab) => {
      shopWin.changePage(tab)
    });
  },
  changePage: (tab) => {
    console.log("change-tab", tab)
    sendToWin('changePage', tab)
    win.show()
  },
  hide: () => {
    if(win) win.hide()
  },
  quit: () => {
    if(win) win.close()
  }
}

module.exports = shopWin
